package Servlet;

import Pojo.Student;
import Service.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class LoginAndResgist extends BaseServlet {

    Service service = new Serviceimply();

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int num;
        String people = req.getParameter("people");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        Student stu = new Student();
        stu.setSname(name);
        stu.setPwd(password);
        HttpSession session = req.getSession();
        if ("student".equals(people)) {
            num = 0;
        } else {
            num = 1;
        }
        Student login = service.login(stu);
        if (login == null) {
            req.setAttribute("msg", "密码或用户名错误!");
            req.setAttribute("username", name);
            req.getRequestDispatcher("index.jsp").forward(req, resp);
        } else {
            session.setAttribute("id", login.getSno());
            session.setAttribute("user", login);
            req.setAttribute("user", login);
            if (login.getState() != num) {
                req.setAttribute("msg", "该用户角色错误");
                req.getRequestDispatcher("index.jsp").forward(req, resp);
            } else {
                if (login.getState() == 0) {
                    req.getRequestDispatcher("studentAndteacherloginsuccess.jsp").forward(req, resp);

                } else {
                    req.getRequestDispatcher("Managersuccess.jsp").forward(req, resp);
                }
            }


        }

    }

    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Student student = new Student();
        String sname = req.getParameter("sname");
        String pwd = req.getParameter("pwd");
        String age = req.getParameter("age");
        String address = req.getParameter("address");
        String people = req.getParameter("people");
        boolean b = service.existBysnameAndpwdPwd(sname,pwd);
        if (b) {
            req.setAttribute("msg", "用户名或密码存在");
            req.setAttribute("username", sname);
            req.getRequestDispatcher("Regist.jsp").forward(req, resp);
        } else {
            if("manger".equals(people)){
                service.add(new Student(null, sname, pwd, age, address, 1));
                req.getRequestDispatcher("RegistSuccess.jsp").forward(req, resp);
            }else {

            service.add(new Student(null, sname, pwd, age, address, 0));
            req.getRequestDispatcher("RegistSuccess.jsp").forward(req, resp);
            }
        }
    }
}
